package org.internna.expensetracker.util;

import static org.springframework.util.StringUtils.hasText;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * Utilities to work with the security context.
 *
 */
public final class SecurityUtils {

    /**
     * Default private constructor for a Utility class.
     */
    private SecurityUtils() {
        throw new AssertionError("Do not try to instantiate utility class");
    }

    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
     }

    public static boolean isAuthenticated() {
    	Authentication auth = getAuthentication();
    	return auth != null && auth.getPrincipal() != null;
    }

    /**
     * The current logged in user.
     *
     * @return any
     */
    public static String getRemoteUser() {
        Authentication auth = getAuthentication();
        if (auth != null) {
        	Object principal = auth.getPrincipal();
        	if (principal instanceof UserDetails) {
        		return ((UserDetails) principal).getUsername();
        	} else if (principal != null) {
        		return principal.toString();
        	}
        }
        return null;
    }

    public static boolean authenticate(AuthenticationManager authenticationManager, String username, String password) {
    	if (hasText(username) && hasText(password)) {
    		try {
    			SecurityContextHolder.clearContext();
    	        Authentication request = new UsernamePasswordAuthenticationToken(username, password);
    	        Authentication result = authenticationManager.authenticate(request);
    	        SecurityContextHolder.getContext().setAuthentication(result);
    	    } catch (AuthenticationException e) {
    	        return false;
    	    }
    	    return true;
    	}
    	return getRemoteUser() != null;
    }

}
